package com.wei.frame.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.CallSuper;
import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.gyf.immersionbar.ImmersionBar;
import com.wei.frame.App;
import com.wei.frame.R;
import com.wei.frame.di.component.AppComponent;
import com.wei.frame.framework.BasePresenter;
import com.wei.frame.framework.IView;
import com.wei.frame.ui.lifecycle.ActivityEvent;
import com.wei.frame.ui.lifecycle.LifecycleProvider;
import com.wei.frame.ui.lifecycle.LifecycleTransformer;
import com.wei.frame.ui.lifecycle.RxLifecycle;
import com.wei.frame.ui.lifecycle.RxLifecycleAndroid;
import com.wei.frame.utils.L;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

/**
 * 作者：赵若位
 * 时间：2020/8/20 2:29
 * 邮箱：1070138445@qq.com
 * 功能：项目中所有Activity的基类
 */
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity
        implements IView, LifecycleProvider<ActivityEvent> {
    protected final String TAG = this.getClass().getSimpleName();

    private final BehaviorSubject<ActivityEvent> mLifecycleSubject = BehaviorSubject.create();

    public abstract int getLayoutId();

    public abstract void bindComponent(@Nullable AppComponent component);

    public abstract void initView();

    public abstract void initData();


    private P mPresenter;
    private Unbinder mUnbinder;
    private View mRootView;

    @Override
    @NonNull
    @CheckResult
    public final Observable<ActivityEvent> lifecycle() {
        return mLifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(mLifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(mLifecycleSubject);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLifecycleSubject.onNext(ActivityEvent.CREATE);
        bindComponent(App.getComponent());
        if (getLayoutId() > 0) {
            setContentView(getLayoutId());
            mUnbinder = ButterKnife.bind(this);
        }
        setStatusColor();
        initView();
        initData();
    }

    /*设置状态的颜色和状态*/
    protected void setStatusColor() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.colorPrimary)
                .init();
    }

    @Override
    @CallSuper
    protected void onStart() {
        super.onStart();
        mLifecycleSubject.onNext(ActivityEvent.START);
    }

    @Override
    @CallSuper
    protected void onResume() {
        super.onResume();
        mLifecycleSubject.onNext(ActivityEvent.RESUME);
    }

    @Override
    @CallSuper
    protected void onPause() {
        mLifecycleSubject.onNext(ActivityEvent.PAUSE);
        super.onPause();
    }

    @Override
    @CallSuper
    protected void onStop() {
        mLifecycleSubject.onNext(ActivityEvent.STOP);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mLifecycleSubject.onNext(ActivityEvent.DESTROY);
        super.onDestroy();
        if (null != mUnbinder && mUnbinder != Unbinder.EMPTY) {
            mUnbinder.unbind();
            mUnbinder = null;
        }
    }


    @Override
    public View getRootView() {
        return null == mRootView ? (mRootView = getLayoutId() > 0 ?
                getWindow().getDecorView().findViewById(android.R.id.content) : null) : mRootView;
    }


    @Override
    public void alert(@Nullable String msg) {
        if (!TextUtils.isEmpty(msg)) {
            runOnUiThread(() -> Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_SHORT).show());
        }
    }

    @Override
    public void log(@Nullable String errorMessge) {
        L.i(new StringBuffer(this.getClass().getName())
                .append(":==>")
                .append(errorMessge).toString());
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showDialog(@javax.annotation.Nullable String message) {

    }

    @Override
    public void openActivity(@Nullable Class<? extends Activity> cls) {
        Intent it = new Intent(this, cls);
        startActivity(it);
    }

    private static long exitTime = 0;//点击后退记录时间

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (this instanceof MainActivity && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                alert(getString(R.string.finish_click_agin));
                exitTime = System.currentTimeMillis();
            } else {
//                ActivityManager.getManager().exit(getApplicationContext());
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


}
